package controllers

import (
	"encoding/base64"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils/pagination"
	"math/rand"
	"net/url"
	"onlinemallv11/beans"
	"smallgift/models"
	"strconv"
	"strings"
	"time"
)

type OrderController struct {
	ApiBaseController
}

// @router /orderlist [post]
func (this *OrderController) OrderList() {
	page, _ := this.GetInt("page", 1)
	rows, _ := this.GetInt("rows", 10)

	send_status := this.GetString("send_status")
	ticket_no := this.GetString("ticket_no")
	phone := this.GetString("phone")
	activityId := this.GetString("activity_id")

	sql := fmt.Sprintf(" SELECT  order_no, ticket_no, name, phone, send_status, receive_date, province ,city, area, address, courier_no, express_company, activity_id, activity.activity_name FROM `order` INNER JOIN activity on order.activity_id = activity.id  WHERE order.ticket_no <> '' ")
	count_sql := fmt.Sprintf(" SELECT  count(*) as total_num FROM `order` where ticket_no <> ''  ")

	var condition_sql string
	if len(send_status) != 0 {
		condition_sql += fmt.Sprintf(" and  `send_status` = '%s' ", send_status)
	}

	if len(ticket_no) != 0 {
		condition_sql += fmt.Sprintf(" and  `ticket_no` = '%s' ", ticket_no)
	}

	if len(phone) != 0 {
		condition_sql += fmt.Sprintf(" and  `phone` = '%s' ", phone)
	}

	if len(activityId) != 0{
		condition_sql += fmt.Sprintf(" and  `activity_id` = '%s' ", activityId)

	}

	sql = sql + condition_sql + fmt.Sprintf(" ORDER BY updated DESC LIMIT  %d,%d ", (page-1)*rows, rows)
	count_sql = count_sql + condition_sql

	beego.Debug(sql)
	beego.Debug(count_sql)

	total_num := TotalNum{}
	o := orm.NewOrm()
	if err := o.Raw(count_sql).QueryRow(&total_num); err != nil {
		this.Data["json"] = BaseBean{"-1", "统计sql报错:" + err.Error()}
		this.ServeJSON()
		return
	}

	int_total_num, _ := strconv.Atoi(total_num.TotalNum)
	p := pagination.NewPaginator(this.Ctx.Request, rows, int_total_num)

	data_list := []NewOrderbean{}

	if _, err := o.Raw(sql).QueryRows(&data_list); err != nil {
		this.Data["json"] = beans.BaseResponse{"-1", "sql报错:" + err.Error()}
		this.ServeJSON()
		return
	}
	beego.Debug(data_list)

	resp_data := OrdersBean{}
	resp_data.Code = "0"
	resp_data.Msg = "SUCCESS"
	resp_data.TotalNum = int_total_num
	resp_data.TotalPage = p.PageNums()
	resp_data.Page = page
	resp_data.Rows = rows
	resp_data.List = data_list

	this.Data["json"] = resp_data
	this.ServeJSON()
	return
}

// @router /edit [post]
func (this *OrderController) Edit() {
	isPickUp := this.GetString("is_pick_up", "N")
	courier_no := this.GetString("courier_no")
	express_company := this.GetString("express_company")
	order_no := this.GetString("order_no")

	if isPickUp == "N" {
		if len(courier_no) == 0 || len(express_company) == 0 || len(order_no) == 0{
			this.Data["json"] = BaseBean{"-1", "参数错误"}
			this.ServeJSON()
			return
		}

		order := models.Order{}
		order.OrderNo = order_no
		if err := order.Read("OrderNo"); err != nil {
			this.Data["json"] = BaseBean{"-1", "编辑错误" + err.Error()}
			this.ServeJSON()
			return
		}

		order.ExpressCompany = express_company
		order.CourierNo = courier_no
		order.SendStatus = "Y"
		if err := order.Update("ExpressCompany", "CourierNo", "SendStatus"); err != nil {
			this.Data["json"] = BaseBean{"-1", "编辑错误" + err.Error()}
			this.ServeJSON()
			return
		}

		this.Data["json"] = BaseBean{"0", "发货成功"}
		this.ServeJSON()
		return
	}else {
		if len(order_no) == 0{
			this.Data["json"] = BaseBean{"-1", "参数错误"}
			this.ServeJSON()
			return
		}

		order := models.Order{}
		order.OrderNo = order_no
		if err := order.Read("OrderNo"); err != nil {
			this.Data["json"] = BaseBean{"-1", "编辑错误" + err.Error()}
			this.ServeJSON()
			return
		}

		order.SendStatus = "P"
		if err := order.Update("SendStatus"); err != nil {
			this.Data["json"] = BaseBean{"-1", "编辑错误" + err.Error()}
			this.ServeJSON()
			return
		}

		this.Data["json"] = BaseBean{"0", "自提成功"}
		this.ServeJSON()
		return
	}


}

// @router /enter [post,get]
func (this *OrderController) Enter() {
	userAgent := this.Ctx.Input.Header("User-Agent")

	if !strings.Contains(userAgent, "MicroMessenger") {
		this.Data["json"] = BaseBean{"-1", "非法渠道"}
		this.ServeJSON()
		return
	}

	activityId := this.GetString("activity_id", "1")
	if len(activityId) == 0 {
		this.Data["json"] = BaseBean{"-1", "参数错误"}
		this.ServeJSON()
		return
	}

	call_back := "http://na.guangfen.net/smallgift/order/authorder?activity_id=" + activityId
	beego.Error(call_back)
	encode_callback := base64.StdEncoding.EncodeToString([]byte(call_back))
	encode_callback = url.QueryEscape(encode_callback)
	beego.Error(encode_callback)
	new_redirect := fmt.Sprintf("http://auth.miaofutech.com/auth/wechat/web?app_id=%s&encode_callback=%s", "wx674925ea2adbee10", encode_callback)
	beego.Error(new_redirect)
	this.Redirect(new_redirect, 302)
	return
}

// @router /authorder [get]
func (this *OrderController) AuthOrder() {

	openId := this.GetString("open_id")
	activityId := this.GetString("activity_id")

	if len(openId) == 0 || len(activityId) == 0 {
		this.Data["json"] = BaseBean{"-1", "参数错误"}
		this.ServeJSON()
		return
	}
	beego.Debug(openId)

	this.Redirect("http://b.miaofutech.com/smallgift/html/index.html"+"?openid="+openId+"&activity_id="+activityId, 302)
	return

}

// @router /orderquery [post]
func (this *OrderController) OrderQuery() {
	openId := this.GetString("openid")
	activityId := this.GetString("activity_id")

	if len(openId) == 0 || len(activityId) == 0{
		this.Data["json"] = BaseBean{"-1", "参数错误"}
		this.ServeJSON()
		return
	}


	//sql := fmt.Sprintf(" SELECT receive_date, ticket_no, province, address, city, area, name, express_company, courier_no, send_status, amount FROM `order` where ticket_no <> '' and open_id = '%s' ", openId)


	sql := fmt.Sprintf(" SELECT order.receive_date, order.ticket_no, order.province, order.address, order.city, order.area, order.name, order.express_company, order.courier_no, order.send_status, activity.activity_amount as amount FROM `order` INNER JOIN activity on order.activity_id = activity.id  WHERE order.ticket_no <> '' and order.open_id = '%s' and order.activity_id = '%s' ", openId, activityId)

	beego.Debug(sql)
	beans := []H5OrderBean{}
	o := orm.NewOrm()
	if _, err := o.Raw(sql).QueryRows(&beans); err != nil && err != orm.ErrNoRows {
		this.Data["json"] = BaseBean{"-1", "sql报错:" + err.Error()}
		this.ServeJSON()
		return
	} else if (err == orm.ErrNoRows) {
		resp_data := H5Order{}
		resp_data.Code = "0"
		resp_data.Msg = "SUCCESS"
		resp_data.Data = beans
		this.Data["json"] = resp_data
		this.ServeJSON()
		return
	} else {
		resp_data := H5Order{}
		resp_data.Code = "0"
		resp_data.Msg = "SUCCESS"
		resp_data.Data = beans
		this.Data["json"] = resp_data
		this.ServeJSON()
		return
	}

}

// @router /orderinsert [post]
func (this *OrderController) OrderInsert() {
	ticket_no := this.GetString("ticket_no")
	ticket_pwd := this.GetString("ticket_pwd")
	name := this.GetString("name")
	phone := this.GetString("phone")
	province := this.GetString("province")
	city := this.GetString("city")
	area := this.GetString("area")
	address := this.GetString("address")
	openId := this.GetString("open_id")
	activityId := this.GetString("activity_id")

	beego.Debug(ticket_no + ":" + ticket_pwd + ":" + name + ":" + phone + ":" + province + ":" + city + ":" + area + ":" + address + ":" + openId)

	if len(ticket_no) == 0 || len(ticket_pwd) == 0 || len(name) == 0 || len(phone) == 0 || len(province) == 0 ||
		len(city) == 0 || len(area) == 0 || len(address) == 0 || len(openId) == 0 || len(activityId) == 0{
		this.Data["json"] = BaseBean{"-1", "参数错误"}
		this.ServeJSON()
		return
	}

	order := models.Order{}
	order.TicketNo = ticket_no
	order.TicketPwd = ticket_pwd
	order.ActivityId, _ = strconv.Atoi(activityId)

	if err := order.Read("TicketNo", "TicketPwd", "ActivityId"); err != nil {
		this.Data["json"] = BaseBean{"-1", "券号密码错误"}
		this.ServeJSON()
		return
	}

	if len(order.OrderNo) != 0 {
		this.Data["json"] = BaseBean{"-1", "该券号已使用"}
		this.ServeJSON()
		return
	}

	orderNo := time.Now().Format("20060102150405") + this.getRandomNumberString(6)
	order.SendStatus = "N"
	order.OpenId = openId
	order.OrderNo = orderNo
	order.Name = name
	order.Phone = phone
	order.Province = province
	order.City = city
	order.Area = area
	order.Address = address
	order.ReceiveDate = time.Now().Format("2006-01-02 15:04:05")
	if err := order.Update(); err != nil {
		this.Data["json"] = BaseBean{"-1", "错误" + err.Error()}
		this.ServeJSON()
		return
	} else {
		this.Data["json"] = BaseBean{"0", "领取成功"}
		this.ServeJSON()
		return
	}

}

func (this *OrderController) getRandomNumberString(l int) string {
	str := "0123456789"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}
